package com.xuecheng.filesystem.service;

import com.alibaba.fastjson.JSON;
import com.xuecheng.filesystem.dao.FileSystemRepository;
import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class FileSystemService {


    private static final Logger LOGGER = LoggerFactory.getLogger(FileSystemService.class);

    @Value("${xuecheng.fastdfs.tracker_servers}")
    String tracker_servers;

    @Value("${xuecheng.fastdfs.connect_timeout_in_seconds}")
    int connect_timeout_in_seconds;

    @Value("${xuecheng.fastdfs.network_timeout_in_seconds}")
    int network_timeout_in_seconds;

    @Value("${xuecheng.fastdfs.charset}")
    String charset;

    @Autowired
    FileSystemRepository fileSystemRepository;

    /**
     * 加载FastDFS的配置
     */
    private void initFastDFS() {
        try {
            //根据tracker服务器地址加载FastDFS
            ClientGlobal.initByTrackers(tracker_servers);
            //设置http连接超时时间
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
            //设置tracker和storage之间的网络通信超时时间
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
            //设置服务器编码
            ClientGlobal.setG_charset(charset);
        } catch (Exception e) {
            e.printStackTrace();
            //返回异常，初始化文件系统错误
            ExceptionCast.cast(FileSystemCode.FS_INITFDFSERROR);
        }
    }

    /**
     * 上传文件的主干函数
     * @param file 文件
     * @param filetag 文件的标签
     * @param businesskey 商业key
     * @param metadata 元数据
     * @return 返回上传结果
     */
    public UploadFileResult upload(MultipartFile file,String filetag,String businesskey,String metadata){
        //上传文件失败
        if(file == null){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }

        //上传文件到fdfs
        String fileId = this.fdfs_upload(file);

        //创建文件信息对象
        FileSystem fileSystem = new FileSystem();
        //文件id
        fileSystem.setFileId(fileId);
        //文件在文件系统中的路径
        fileSystem.setFilePath(fileId);

        fileSystem.setFiletag(filetag);
        fileSystem.setBusinesskey(businesskey);

        //存在元数据
        if(StringUtils.isNotEmpty(metadata)){
            try {
                Map map = JSON.parseObject(metadata, Map.class);
                fileSystem.setMetadata(map);
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

        //名称
        fileSystem.setFileName(file.getOriginalFilename());
        //大小
        fileSystem.setFileSize(file.getSize());
        //文件类型
        fileSystem.setFileType(file.getContentType());

        //调用dao对象
        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS,fileSystem);

    }

    /**
     * 获取上传文件的id
     * @param file 要上传的文件
     * @return 返回id
     */
    public String fdfs_upload(MultipartFile file) {

        try {
//        加载初始化配置,就是从yaml把文件的值弄出来
            initFastDFS();
            //创建tracker client
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storeStorage);
            //上传文件
            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            //文件的扩展名
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //文件的id
            String file1 = storageClient1.upload_file1(bytes, extName, null);
            //返回文件id
            return file1;
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }

        return null;

    }
}
